export function initAnchor() {
  var nav = $('#nav .nav-main .main-item')
  var anchor = $('#nav .nav-main .anchor')
  // 获取精确的width 
  var init_width = getDecimalWidth(nav[0])
  var init_left = getDecimalWidth($('#nav .nav-main')[0])
  // 获取left
  var activeIndex = 0
  nav.each(function (index) {
    // 查找当活跃的a标签并获取index
    if ($(this).find('a').hasClass('router-link-exact-active')) {
      activeIndex = index
    }
    init_left -= getDecimalWidth($(this)[0])
    // 当活跃标签下标>0 并且当前循环为最后一次
    if (activeIndex > 0 && index === nav.length - 1) {
      for (var i = 0; i < activeIndex; i++) {
        init_left += getDecimalWidth(nav[i])
      }
    }
  })
  var active_width = init_width
  var active_left = init_left
  // 设置初始值
  anchor.css('width', init_width + 'px')
  anchor.css('left', init_left + 'px')
  nav.each(function (index) {
    // 当前元素宽度
    var width = getDecimalWidth($(this)[0])
    $(this).hover(function () {
      var left = init_left
      if (index < activeIndex) {
        for (var i = activeIndex - index; i > 0; i--) {
          left -= getDecimalWidth(nav[i])
        }
      } else {
        for (var i = 0; i < index - activeIndex; i++) {
          left += getDecimalWidth(nav[i])
        }
      }
      anchor.css('width', width + 'px')
      anchor.css('left', left + 'px')
    })
    $(this).click(function () {
      var left = init_left
      if (index < activeIndex) {
        for (var i = activeIndex - index; i > 0; i--) {
          left -= getDecimalWidth(nav[i])
        }
      } else {
        for (var i = 0; i < index - activeIndex; i++) {
          left += getDecimalWidth(nav[i])
        }
      }
      anchor.css('width', width + 'px')
      anchor.css('left', left + 'px')
      //更改初始值
      active_width = width
      active_left = left
    })
    $(this).mouseleave(function () {
      anchor.css('width', active_width + 'px')
      anchor.css('left', active_left + 'px')
    })
  })

  window.onload = function() {
    initAnchor()
  }

  window.onresize = function() {
    initAnchor()
  }
}

function getDecimalWidth(element) {
  var width = Number(window.getComputedStyle(element).width.replace('px', ''))
  return Number(width.toFixed(2))
}
